<template>
  <div class="table-item no-header-border">
    <p v-if="isShowTitle" :style="getTitleStyle()" class="item-header">{{ title }}<tipIcon v-if="RemarkOptions.showRemark && RemarkOptions.value" :content="RemarkOptions.value" class="ml4"/></p>
    <!-- class="default-scroll-table" -->
    <u-table
      :ref="`table-item-`+moduleItemData.id"
      :data="rows"
      :row-class-name="tableRowClassName"
      :summary-method="getSummaries"
      :height="tableHeight"
      :show-summary="!!(moduleItemData.collectColumn && moduleItemData.collectColumn.field && moduleItemData.collectColumn.field.length)"
      :header-cell-style="tableTailConfig"
      :cell-style="tableMidConfig"
      :row-style="getRowColor"
      :row-height="tableColumnHeight"
      size="mini"
      use-virtual
      border
      header-row-class-name="table-header">
      <u-table-column
        v-for="(itemCol, indexCol) in columns"
        :label="itemCol"
        :key="indexCol"
        :prop="indexCol.toString()"
        :min-width="diyTableWidth[itemCol]?`${diyTableWidth[itemCol]}` : ''"
        align="center"
        sortable
        header-align="center"
      >
        <template slot-scope="scope">
          <div v-if="itemCol.indexOf('编号') >= 0 || itemCol.indexOf('序号') >= 0">{{ scope.row[indexCol] }}{{ getFieldData(itemCol).unit }}</div>
          <div v-else-if="getFieldData(itemCol).optionsType === 2 || getFieldData(itemCol).optionsType === null" class="ellipsisOne">
            <el-tooltip v-if="scope.row[indexCol]" placement="top">
              <div slot="content">{{ scope.row[indexCol] | moneyFilterData }}{{ getFieldData(itemCol).unit }}</div>
              <div class="ellipsisOne">{{ scope.row[indexCol] | tableDatafilter }}{{ getFieldData(itemCol).unit }}</div>
            </el-tooltip>
            <div v-else class="ellipsisOne">{{ scope.row[indexCol] | tableDatafilter }}{{ getFieldData(itemCol).unit }}</div>
          </div>
          <ToolTip v-else :content="scope.row[indexCol]" />
        </template>
      </u-table-column>
    </u-table>
  </div>
</template>

<script>
import { isNumber } from '@/utils/tools';
import { moneyFilter, numberTextFormat } from '@/filters/number';
export default {
  name: 'TableItem',
  filters: {
    tableDatafilter(val) {
      if (!isNumber(val)) {
        return val || '--';
      } else {
        const num = numberTextFormat(val, 1);
        if (isNaN(Number(num))) {
          return num;
        }
        return moneyFilter(num, false);
      }
    },
    moneyFilterData(val) {
      if (!isNumber(val)) {
        return val || '--';
      } else {
        return moneyFilter(val);
      }
    }
  },
  props: {
    columns: {
      type: Array,
      default: () => []
      // default: () => ['日期', '访问用户', '下单用户', '下单率']
    },
    rows: {
      type: Array,
      default: () => []
      // default: () => [['1/1', 1393, 5000, 50], ['1/2', 500, 4000, 32], ['1/2', 500, 4000, 32], ['1/2', 500, 4000, 32], ['1/2', 500, 4000, 32]]
    },
    moduleItemData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    showAreaMaxHeight: {
      type: Number,
      default: 100
    },
    // 全局的样式，修改标题边距
    chartConfig: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      // optionsType  0:文本型 1:  时间日期  2: 数值型   3: 部门
    };
  },
  computed: {
    styleConfig() {
      return this.moduleItemData.styleConfig;
    },
    title() {
      return this.moduleItemData.name;
    },
    isShowTitle() {
      return this.title && (this.getTitleStyle() && !this.getTitleStyle().isHide);
    },
    values() {
      return this.rows && this.rows.length > 0 ? this.rows[0] : [];
    },
    diyTableWidth() {
      const diyTableWidth = this.styleConfig.diyTableWidth || {};
      return diyTableWidth;
    },
    tableMidConfig() {
      const tableMidConfig = this.styleConfig.tableMidConfig || {};
      const fontSize = tableMidConfig.fontSize ? tableMidConfig.fontSize + 'px' : '14px';
      const tableColumnHeight = tableMidConfig.tableColumnHeight ? tableMidConfig.tableColumnHeight + 'px' : '32px';
      return {
        ...tableMidConfig,
        fontSize,
        height: tableColumnHeight
      };
    },
    tableColumnHeight() {
      const tableMidConfig = this.styleConfig.tableMidConfig || {};
      const tableColumnHeight = tableMidConfig.tableColumnHeight ? tableMidConfig.tableColumnHeight : 32;
      return Number(tableColumnHeight);
    },
    tableTailConfig() {
      const tableTailConfig = this.styleConfig.tableTailConfig || {};
      this.setTableGutterStyle(tableTailConfig.headBgColor || '#85A2FF');
      return {
        color: tableTailConfig.color || '#fff',
        fontSize: tableTailConfig.fontSize ? tableTailConfig.fontSize + 'px' : '14px',
        height: tableTailConfig.tableColumnHeight ? tableTailConfig.tableColumnHeight + 'px' : '32px',
        backgroundColor: tableTailConfig.headBgColor || '#85A2FF'
      };
    },
    tableHeight() {
      if (this.isShowTitle) {
        return `${Math.abs(this.showAreaMaxHeight - this.getTitleFontSize() - 16)}px`;
      }
      return `${this.showAreaMaxHeight}px`;
    },
    RemarkOptions() {
      return (this.getTitleStyle() && this.getTitleStyle().RemarkOptions) || {};
    }
  },
  methods: {
    setTableGutterStyle(bgColor) {
      this.$nextTick(() => {
        const tableRef = this.$refs[`table-item-${this.moduleItemData.id}`];
        const gutter = tableRef && tableRef.$el.querySelector('.table-header .gutter');
        if (gutter) {
          gutter.style.backgroundColor = bgColor;
          gutter.style.borderColor = bgColor;
        }
      });
    },
    getFieldData(columnName) {
      const item = this.moduleItemData.selectField.find(i => i.columnName === columnName);
      return item || {};
    },
    tableRowClassName({ row, rowIndex }) {
      return rowIndex % 2 ? 'double-row' : 'single-row';
    },
    getValue(index) {
      return index < this.values.length ? this.values[index] : '--';
    },
    /**
     * 自定义样式
     */
    getTitleStyle() {
      const styleConfig = this.styleConfig;
      let styleObj = {};
      if (styleConfig && styleConfig instanceof Array) {
        // 兼容旧数据
        return this.moduleTitleSy();
      } else if (styleConfig && styleConfig instanceof Object) {
        styleObj = { ...styleConfig.moduleName };
        styleObj.lineHeight = styleObj.fontSize = styleObj.fontSize + 'px'; // 避免字体造成高度计算错误
        styleObj.marginBottom = this.chartConfig.modulePadding ? this.chartConfig.modulePadding + 'px' : '12px';
        if (styleObj.FontStyle && styleObj.FontStyle instanceof Array) {
          if (styleObj.FontStyle.includes('italic')) styleObj.fontStyle = 'italic';
          if (!styleObj.FontStyle.includes('bolder')) styleObj.fontWeight = 'normal';
        }
        return styleObj;
      } else {
        return {};
      }
    },
    getRowColor({ row, rowIndex }) {
      const styleConfig = this.styleConfig;
      const rowConfig = {};
      if (styleConfig.tableMidConfig && styleConfig.tableMidConfig.evenBgColor && styleConfig.tableMidConfig.oddBgColor) {
        rowConfig.backgroundColor = rowIndex % 2 ? styleConfig.tableMidConfig.evenBgColor : styleConfig.tableMidConfig.oddBgColor;
      }
      return rowConfig;
    },
    getTitleFontSize() {
      const styleConfig = this.styleConfig;
      if (styleConfig && styleConfig instanceof Array) {
        // 兼容旧数据
        return 32;
      } else if (styleConfig && styleConfig instanceof Object && styleConfig.moduleName) {
        return styleConfig.moduleName.fontSize;
      } else {
        return 0;
      }
    },
    moduleTitleSy() {
      const moduleTitleStyle = {};
      this.styleConfig.map(item => {
        if (item.title === '模块名称：') {
          item.config.forEach(val => {
            if (val.word === 'fontSize' && val.unit) {
              if (val.value.toString().indexOf('px') === -1) {
                val.value = `${val.value}${val.unit}`;
              }
            }
            moduleTitleStyle[val.word] = val.value;
          });
        }
      });
      return moduleTitleStyle;
    },
    // 汇总行
    getSummaries({ columns, data }) {
      const sums = [];
      const collectColumn = this.moduleItemData.collectColumn;
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = collectColumn ? collectColumn.title : '总计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          const collectColumnItem = collectColumn.field.find(i => i.columnName === column.label);
          const collectColumnType = collectColumnItem && collectColumnItem.columnName ? collectColumnItem.type : 1;
          /** 求和 */
          let sum = 0;
          sums[index] = values.forEach(curr => {
            sum += Number(curr);
          });
          if (collectColumnType === 0) {
            /** 平均 */
            sum = sum / values.length;
          }
          const unit = this.getFieldData(column.label).unit || '';
          sums[index] = this.handelData(sum) + unit;
        } else {
          sums[index] = '--';
        }
      });
      return [sums];
    },
    handelData(val) {
      if (!isNumber(val)) {
        return val || '--';
      } else {
        return moneyFilter(numberTextFormat(val, 1), false);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.table-item {
  .item-header {
    font-size:20px;
    font-weight: bolder;
    color:rgba(51,51,51,1);
    // padding: 0 8px;
    margin: 0 0 12px 0;
    // border-left: 4px solid rgba(64,110,255,1);
  }
  ::v-deep .el-table {
    // .el-table__body-wrapper::-webkit-scrollbar, .el-table__fixed-body-wrapper::-webkit-scrollbar   {
    //   width: 6px !important;
    // }
    .table-item-header {
      .label {
        display: flex;
        align-items: center;
        height: 100%;
      }
    }
    .caret-wrapper {
      height: auto;
      .sort-caret {
        &.descending {
          border-top-color: rgba($color: #ffffff, $alpha: 0.3);
          bottom: -11px;
        }
        &.ascending {
          border-bottom-color: rgba($color: #ffffff, $alpha: 0.3);
          top: -11px;
        }
      }
    }
    .ascending {
      .sort-caret {
        &.ascending {
          border-bottom-color: #fff
        }
      }
    }
    .descending {
      .sort-caret {
        &.descending {
          border-top-color: #fff
        }
      }
    }
    .el-table__footer {
      .gutter {
        background-color: #f5f7fa;
      }
    }
    .table-header {
      .is-leaf {
        border-left: 1px solid #fff;;
        border-right: none;
        border-bottom: 1px solid transparent;
        &:first-child{
          border-left: none;
        }
      }
    }
    .table-header > th {
      background: #fff;
      font-size:14px;
      padding: 0;
      &> .cell {
        display: flex;
        align-items: center;
        justify-content: center;
        color: inherit;
      }
    }
    .double-row {
      background: #CED5F6;
      &:hover {
        td {
          background: #CED5F6;
        }
      }
    }
    .single-row {
      background: #EAEDFF;
      padding: 0;
      &:hover {
        td {
          background: #EAEDFF;
        }
      }
    }

    .el-table__footer-wrapper {
      td {
        font-size: 14px;
        line-height: 1.2;
        padding: 0;
      }
    }
    .double-row, .single-row  {
      td {
        font-size: 14px;
        padding: 0;
        line-height: 1.2;
        border-left: 1px solid #fff;
        border-right: none;
        border-bottom: 1px solid transparent;
        &:first-child{
          border-left: none;
        }
      }
    }
  }
}
.no-header-border {
  ::v-deep .el-table {
    .table-header {
      .gutter {
        border-bottom: 1px solid #fff;
      }
      // .is-leaf {
      //   border-left: none;
      //   border-right: 1px solid transparent;
      //   border-bottom: 1px solid transparent;
      //   &:last-child{
      //     border-right: none;
      //   }
      // }
    }
  }
}
</style>
